const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const { Worker } = require('worker_threads')

let mainWindow

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })

  mainWindow.loadFile('index.html')
  // mainWindow.webContents.openDevTools()
}

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', () => {
  if (mainWindow === null) createWindow()
})

// 处理来自渲染进程的计算请求
ipcMain.handle('calculate-add', async (event, num1, num2) => {
  return new Promise((resolve, reject) => {
    // 创建worker线程来处理WebAssembly计算
    const worker = new Worker(path.join(__dirname, 'calculator-worker.js'))
    
    worker.postMessage({ num1, num2 })
    
    worker.on('message', (result) => {
      worker.terminate()
      resolve(result)
    })

    worker.on('error', (error) => {
      worker.terminate()
      reject(error)
    })
  })
})